const express = require('express')
const { param, validationResult } = require('express-validator')
const { query: dbQuery, transaction } = require('../config/database')
const {
  authenticateToken,
  optionalAuth,
  requireVip
} = require('../middleware/auth')

const router = express.Router()

/**
 * @swagger
 * /api/chapters/{id}:
 *   get:
 *     summary: 获取章节内容
 *     tags: [章节]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 章节ID
 *     responses:
 *       200:
 *         description: 获取成功
 *       402:
 *         description: 需要付费
 *       403:
 *         description: 需要VIP权限
 */
router.get(
  '/:id',
  [param('id').isInt({ min: 1 }).withMessage('章节ID必须是正整数')],
  optionalAuth,
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const chapterId = req.params.id

      // 获取章节信息
      const chapters = await dbQuery(
        `
      SELECT 
        c.id, c.novel_id, c.title, c.content, c.chapter_number, 
        c.word_count, c.is_vip, c.price, c.view_count, c.created_at,
        n.title as novel_title, n.author as novel_author
      FROM chapters c
      JOIN novels n ON c.novel_id = n.id
      WHERE c.id = ?
    `,
        [chapterId]
      )

      if (chapters.length === 0) {
        return res.error('章节不存在', 'CHAPTER_NOT_FOUND', 404)
      }

      const chapter = chapters[0]

      // 检查权限
      let canRead = true
      let needPayment = false
      let needVip = false

      if (chapter.is_vip) {
        if (!req.user) {
          canRead = false
          needVip = true
        } else if (!req.user.is_vip) {
          // 检查用户是否已购买此章节
          if (chapter.price > 0) {
            // 这里简化处理，实际项目中应该有章节购买记录表
            // 目前直接检查用户书币是否足够
            if (req.user.coins < chapter.price) {
              canRead = false
              needPayment = true
            } else {
              // 扣除书币并记录购买
              await transaction(async connection => {
                await connection.execute(
                  'UPDATE users SET coins = coins - ? WHERE id = ?',
                  [chapter.price, req.user.id]
                )

                // 这里应该插入购买记录，暂时省略
              })
            }
          } else {
            canRead = false
            needVip = true
          }
        }
      }

      // 如果不能阅读，返回受限内容
      if (!canRead) {
        const limitedChapter = {
          ...chapter,
          content:
            chapter.content.substring(0, 200) +
            '\n\n...\n\n[此章节需要VIP权限或书币购买]'
        }

        delete limitedChapter.content // 完全不返回内容

        return res.error(
          needVip ? '此章节需要VIP权限' : `此章节需要${chapter.price}书币购买`,
          needVip ? 'VIP_REQUIRED' : 'PAYMENT_REQUIRED',
          needVip ? 403 : 402
        )
      }

      // 增加浏览量
      await dbQuery(
        'UPDATE chapters SET view_count = view_count + 1 WHERE id = ?',
        [chapterId]
      )
      chapter.view_count += 1

      // 记录阅读历史
      if (req.user) {
        await dbQuery(
          `
        INSERT INTO reading_history (user_id, novel_id, chapter_id, reading_time)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE reading_time = reading_time + VALUES(reading_time)
      `,
          [req.user.id, chapter.novel_id, chapterId, 1]
        )

        // 更新书架阅读进度
        await dbQuery(
          `
        INSERT INTO user_bookshelf (user_id, novel_id, last_read_chapter_id, last_read_at)
        VALUES (?, ?, ?, NOW())
        ON DUPLICATE KEY UPDATE 
          last_read_chapter_id = VALUES(last_read_chapter_id),
          last_read_at = VALUES(last_read_at)
      `,
          [req.user.id, chapter.novel_id, chapterId]
        )
      }

      // 获取上一章和下一章
      const prevChapter = await dbQuery(
        `
      SELECT id, title, chapter_number 
      FROM chapters 
      WHERE novel_id = ? AND chapter_number < ?
      ORDER BY chapter_number DESC 
      LIMIT 1
    `,
        [chapter.novel_id, chapter.chapter_number]
      )

      const nextChapter = await dbQuery(
        `
      SELECT id, title, chapter_number 
      FROM chapters 
      WHERE novel_id = ? AND chapter_number > ?
      ORDER BY chapter_number ASC 
      LIMIT 1
    `,
        [chapter.novel_id, chapter.chapter_number]
      )

      res.success(
        {
          chapter,
          navigation: {
            prev: prevChapter || null,
            next: nextChapter || null
          }
        },
        '获取章节成功'
      )
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/chapters/{id}/unlock:
 *   post:
 *     summary: 解锁VIP章节
 *     tags: [章节]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 章节ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               paymentMethod:
 *                 type: string
 *                 enum: [coins, vip]
 *                 description: 支付方式
 *     responses:
 *       200:
 *         description: 解锁成功
 */
router.post(
  '/:id/unlock',
  [
    authenticateToken,
    param('id').isInt({ min: 1 }).withMessage('章节ID必须是正整数')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const chapterId = req.params.id
      const { paymentMethod = 'coins' } = req.body

      // 获取章节信息
      const chapters = await dbQuery(
        `
      SELECT id, novel_id, title, is_vip, price
      FROM chapters 
      WHERE id = ?
    `,
        [chapterId]
      )

      if (chapters.length === 0) {
        return res.error('章节不存在', 'CHAPTER_NOT_FOUND', 404)
      }

      const chapter = chapters[0]

      if (!chapter.is_vip) {
        return res.error('此章节无需解锁', 'CHAPTER_FREE')
      }

      if (paymentMethod === 'vip') {
        if (!req.user.is_vip) {
          return res.error('您不是VIP用户', 'NOT_VIP', 403)
        }
        // VIP用户直接解锁
        res.success(null, 'VIP章节解锁成功')
      } else if (paymentMethod === 'coins') {
        if (req.user.coins < chapter.price) {
          return res.error(
            `书币不足，需要${chapter.price}书币`,
            'INSUFFICIENT_COINS'
          )
        }

        // 扣除书币
        await transaction(async connection => {
          await connection.execute(
            'UPDATE users SET coins = coins - ? WHERE id = ?',
            [chapter.price, req.user.id]
          )

          // 记录章节购买（这里简化，实际应该有专门的购买记录表）
          // 可以在这里插入purchase_records表
        })

        res.success(
          {
            remainingCoins: req.user.coins - chapter.price
          },
          '章节解锁成功'
        )
      } else {
        return res.error('无效的支付方式', 'INVALID_PAYMENT_METHOD')
      }
    } catch (error) {
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/chapters/{id}/report-reading-time:
 *   post:
 *     summary: 上报阅读时间
 *     tags: [章节]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 章节ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - readingTime
 *             properties:
 *               readingTime:
 *                 type: integer
 *                 description: 阅读时间（秒）
 *     responses:
 *       200:
 *         description: 上报成功
 */
router.post(
  '/:id/report-reading-time',
  [
    authenticateToken,
    param('id').isInt({ min: 1 }).withMessage('章节ID必须是正整数')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.error(errors.array()[0].msg, 'VALIDATION_ERROR')
      }

      const chapterId = req.params.id
      const { readingTime } = req.body

      if (!readingTime || readingTime < 1) {
        return res.error('阅读时间必须大于0', 'INVALID_READING_TIME')
      }

      // 获取章节信息
      const chapters = await dbQuery(
        'SELECT novel_id FROM chapters WHERE id = ?',
        [chapterId]
      )

      if (chapters.length === 0) {
        return res.error('章节不存在', 'CHAPTER_NOT_FOUND', 404)
      }

      const chapter = chapters[0]

      // 记录阅读历史
      await dbQuery(
        `
      INSERT INTO reading_history (user_id, novel_id, chapter_id, reading_time)
      VALUES (?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE reading_time = reading_time + VALUES(reading_time)
    `,
        [req.user.id, chapter.novel_id, chapterId, readingTime]
      )

      // 更新用户总阅读时间
      await dbQuery(
        'UPDATE users SET reading_time = reading_time + ? WHERE id = ?',
        [readingTime, req.user.id]
      )

      res.success(null, '阅读时间记录成功')
    } catch (error) {
      next(error)
    }
  }
)

module.exports = router
